/**
 * @description  : 案件统计
 * @descriptionDetail : 案件统计
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-12-05 13:56:42
 */
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
      <view class="nav-right-icon">
        <u-icon name="reload" color="#FFF" @tap="refreshTb()"></u-icon>
        <u-icon style="margin-left: 20rpx" name="more-dot-fill" color="#FFF" @tap="showSearch = true"></u-icon>
      </view>
    </theme-navbar>
    <!-- #endif -->
    <!-- #ifdef H5-DINGDING || H5-WECHAT || H5-EMP -->
    <fab-button :content="fContent" @fabtrigger="fabtrigger" />
    <!-- #endif -->
    <view class="content u-page">
      <swiper-stats-com :totalTitle="orginalData.content.length == 1 ? orginalData.content[0].org_name : '合计'"
        :hasTotalRow="hasTotal" :needCalcTotal="false" :totalEndOrStart="hasTotal" :fixedLimit="10" :keyCode="keyCode"
        :itemKeyUuid="itemKeyUuid" :orginalData="orginalData" :height="swiperHeight" areaKey="org_name" @dbClick="dbClick"
        @clickItem="clickItem"></swiper-stats-com>
      <u-tabbar bg-color="#F7F7F9" activeColor="rgb(0 112 210)" v-model="tabCurrent" :list="tabList" icon-size="40" :height="100"
        @change="tabChange"></u-tabbar>
    </view>
    <u-popup mode="right" length="80%" v-model="showSearch" :mask-close-able="maskCanClose">
      <case-search-com ref="lscRef" :regs="regs" :endDate="endDate" :curTimeStart="curTimeStart" :currentPro="currentPro"
        :curTimeEnd="curTimeEnd" @choiceTime="timeChoice" @search="searchTap" @currentFn="currentFn"
        @clearCurrent="clearCurrent"></case-search-com>
    </u-popup>
    <u-picker :startYear="startYear" :endYear="endYear" v-model="showTime" mode="time" :params="pickParam"
      @confirm="timeChange"></u-picker>
  </view>
</template>
<script>
import SwiperStatsCom from './components/swiper-stats-com.vue';
import CaseSearchCom from './components/caseSearchCom.vue';
import reportService from '@/service/report/report.service.js';
import commonService from '@/service/common/common.service.js';
import moment from 'moment';
import fabButton from '@/components/uni-fab.vue';
export default {
  components: {
    SwiperStatsCom,
    CaseSearchCom,
    fabButton,
  },
  data () {
    return {
      hasTotal: true, // 是否需要合计
      from: 'ajzj', // ajzj  zyaj  jyaj zsyaj
      currentPro: 0,
      user: this.$store.state.userInfo,
      keyCode: 'org_uuid',
      itemKeyUuid: '',
      itemKeyName: '',
      pickParam: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false,
        timestamp: true, // 1.3.7版本提供
      },
      fromEnum: {
        ajzj: {
          name: '案件总计',
          propType: '',
        },
        zyaj: {
          name: '真烟案件',
          propType: '01',
        },
        jyaj: {
          name: '假烟案件',
          propType: '02',
        },
        zsyaj: {
          name: '走私烟案件',
          propType: '03',
        },
      },
      regs: '',
      showSearch: false,
      showTime: false,
      maskCanClose: true,
      tabCurrent: 0,
      endDate: '',
      curTimeStart: moment().startOf('year').format('YYYY-MM-DD'),
      curTimeEnd: moment().subtract(1, 'days').format('YYYY-MM-DD'),
      endYear: new Date().getFullYear(),
      startYear: 1950,
      tabList: [{
        iconPath: '../../../static/query/icon_qy2.png',
        selectedIconPath: '../../../static/query/icon_qy.png',
        text: '区域',
        header: [
          [{
            label: '',
            fieldKey: 'org_name',
            columnSpan: 3,
            hasSort: false,
            unit: '起',
            align: 'center',
          },
          {
            label: '案件数',
            fieldKey: 'c_case_count',
            columnSpan: 3,
            hasSort: true,
            align: 'right',
          },
          {
            label: '占比',
            fieldKey: 'proportion_c_case_count',
            columnSpan: 3,
            hasSort: true,
            align: 'right',
          },
          {
            label: '同比',
            fieldKey: 'percent_c_case_count',
            columnSpan: 3,
            hasSort: true,
            align: 'right',
          },
          ],
          [{
            label: '',
            fieldKey: 'org_name',
            columnSpan: 3,
            hasSort: false,
            unit: '件',
            align: 'center',
          },
          {
            label: '卷烟数',
            fieldKey: 'g_count',
            columnSpan: 3,
            hasSort: true,
            align: 'right',
          },
          {
            label: '占比',
            fieldKey: 'proportion_g_count',
            columnSpan: 3,
            hasSort: true,
            align: 'right',
          },
          {
            label: '同比',
            fieldKey: 'percent_g_count',
            columnSpan: 3,
            hasSort: true,
            align: 'right',
          },
          ],
          [{
            label: '',
            fieldKey: 'org_name',
            columnSpan: 3,
            hasSort: false,
            unit: '万元',
            align: 'center',
          },
          {
            label: '案值',
            fieldKey: 'case_total_val',
            columnSpan: 3,
            hasSort: true,
            align: 'right',
          },
          {
            label: '占比',
            fieldKey: 'proportion_case_total_val',
            columnSpan: 3,
            hasSort: true,
            align: 'right',
          },
          {
            label: '同比',
            fieldKey: 'percent_case_total_val',
            columnSpan: 3,
            hasSort: true,
            align: 'right',
          },
          ],
        ],
      },
      {
        iconPath: '../../../static/query/brand2.png',
        selectedIconPath: '../../../static/query/brand.png',
        text: '品牌',
        header: [
          [{
            label: '',
            fieldKey: 'goodsName',
            columnSpan: 3,
            hasSort: false,
            unit: '件',
            align: 'left',
          },
          {
            label: '卷烟数',
            fieldKey: 'totalQty',
            columnSpan: 3,
            hasSort: true,
            align: 'right',
          },
          {
            label: '占比',
            fieldKey: 'cig_case_qty_zb',
            columnSpan: 3,
            hasSort: true,
            align: 'right',
          },
          {
            label: '同比',
            fieldKey: 'percent_totalQty',
            columnSpan: 3,
            hasSort: true,
            align: 'right',
          },
          ],
        ],
      },
      ],
      swiperHeight: 0,
      orginalData: {
        header: [],
        content: [],
      },
      orgParam: {
        // org层级相关参数
        orgUuid: '',
        parentOrgUuid: '',
        orgName: '',
        parentOrgName: '',
        orgRank: 1, // 下钻默认是1 表示当前
      },
      fContent: [{
        iconPath: require('@/static/refresh.png'),
        selectedIconPath: require('@/static/refresh.png'),
        text: '刷新',
        active: false,
      },
      {
        iconPath: require('@/static/sou.png'),
        selectedIconPath: require('@/static/sou.png'),
        text: '筛选',
        active: false,
      },
      ],
    };
  },
  onLoad (opt) {
    this.from = opt.from || 'ajtj';
    this.showDefaultTitle = false;
  },
  watch: {
    showTime (v) {
      // 调用钉钉标题接口，动态设置展示标题
      this.maskCanClose = !v;
    },
  },
  mounted () {
    // this.setRightBtns();
    this.updateMixinTitle(this.fromEnum[this.from].name);
    this.tabList.forEach((itm) => {
      itm.header.forEach((ip) => {
        ip[0].label = this.fromEnum[this.from].name;
      });
    });
    this.init();
    this.currentFn();
  },
  methods: {
    init () {
      // #ifdef H5-DINGDING
      this.swiperHeight = this.$u.sys().windowHeight - 50;
      // #endif
      // #ifndef H5-DINGDING
      this.swiperHeight = this.$u.sys().windowHeight - 44 - 50;
      // #endif
      commonService.queryAreaBaseByCode(this.user.user.org.orgUuid).then((res) => {
        if (!res.success) return;
        let areaName = '';
        let areaCode = '';
        areaName = res.bean.proname;
        areaCode = res.bean.procode;
        this.orgParam.orgName = areaName;
        this.orgParam.areaName = areaName;
        this.orgParam.areaCode = areaCode;
        this.regs = this.orgParam.orgName;
      });
      this.orgParam.parentOrgUuid = '';
      this.orgParam.orgLevel = '01';
      this.orgParam.orgUuid = this.user.user.org.orgUuid; // 默认都用自己地区的code
      this.orginalData.header = this.tabList[this.tabCurrent].header;
      this.loadData();
    },
    currentFn (e) {
      this.currentPro = e;
    },
    clearCurrent () {
      this.currentPro = 0;
    },
    setRightBtns () {
      // 设置右侧标题
      // #ifdef H5-DINGDING
      this.$deviceApi.setMenu([{
        id: '1',
        text: '刷新',
      },
      {
        id: '2',
        text: '更多',
      },
      ],
        (res) => {
          if (res.id == '1') {
            this.refreshTb();
          } else {
            // 弹出more
            this.showSearch = true;
          }
        }
      );
      // #endif
    },
    loadData () {
      this.$modal.showLoading('查询中...');
      let cts = this.curTimeStart;
      let cte = this.curTimeEnd;
      let param = {
        dimensionType: this.tabCurrent, // 0 区域  1 品牌
        orgLevel: this.orgParam.orgLevel,
        orgRank: this.orgParam.orgRank,
        startTime: cts,
        endTime: cte,
        propType: this.fromEnum[this.from].propType,
        orgUuid: this.orgParam.orgUuid,
        parentOrgUuid: this.orgParam.parentOrgUuid,
      };
      if (this.tabCurrent == 1) {
        param.orgLevel = this.orgParam.orgLevel;
      }
      if (this.tabCurrent == 1 && !this.$u.test.isEmpty(this.itemKeyUuid)) {
        param.parentOrgUuid = this.orgParam.orgUuid;
        param.orgUuid = this.itemKeyUuid;
        this.regs = this.itemKeyName;
      } else {
        this.regs = this.orgParam.orgName;
      }
      let params = {
        paras: {
          orgUuid: param.orgUuid,
          comparedShow: '1',
          caseDateType: '2',
          startDate: cts,
          endDate: cte,
          methods: 'ctCaseCount,ctCaseGoodsCount,ctGoodsPropType,ctCaseVal',
          PROP_TYPE: this.fromEnum[this.from].propType,
        },
      };
      if (this.tabCurrent == 0) {
        this.hasTotal = true;
        reportService
          .caseStatisticsList(params)
          .then((res) => {
            this.$modal.hideLoading();
            if (res.success) {
              // 如果合计在最后一行
              if (res.data.length > 0) {
                let totalRow = res.data[res.data.length - 1];
                if (totalRow.org_name == '全省') {
                  res.data.splice(res.data.length - 1, 1);
                  res.data.unshift(totalRow);
                }
                if (this.hasTotal) {
                  let num1 = 0;
                  let num2 = 0;
                  let num3 = 0;
                  for (let i = 1; i < res.data.length; i++) {
                    if (res.data[i].c_case_count) {
                      num1 += parseFloat(res.data[i].c_case_count);
                    }
                    if (res.data[i].g_count) {
                      num2 += parseFloat(res.data[i].g_count);
                    }
                    if (res.data[i].case_total_val) {
                      num3 += parseFloat(res.data[i].case_total_val);
                    }
                  }
                  res.data[0].c_case_count = num1;
                  res.data[0].g_count = num2;
                  res.data[0].case_total_val = num3;
                }
                res.data.forEach((item) => {
                  if (!item.case_total_val) {
                    item.case_total_val = 0;
                  }
                  if (item.c_case_count) {
                    item.proportion_c_case_count = ((item.c_case_count / res.data[0].c_case_count) * 100).toFixed(2) + '%';
                  } else {
                    item.proportion_c_case_count = '';
                  }
                  if (item.g_count) {
                    item.proportion_g_count = ((item.g_count / res.data[0].g_count) * 100).toFixed(2) + '%';
                  } else {
                    item.proportion_g_count = '';
                  }
                  if (item.case_total_val) {
                    item.proportion_case_total_val = ((item.case_total_val / res.data[0].case_total_val) * 100).toFixed(2) + '%';
                  } else {
                    item.proportion_case_total_val = '';
                  }

                  if (item.proportion_c_case_count) {
                    item.proportion_c_case_count = Number(item.proportion_c_case_count.replace('%', ''));
                  }
                  if (item.proportion_g_count) {
                    item.proportion_g_count = Number(item.proportion_g_count.replace('%', ''));
                  }
                  if (item.proportion_case_total_val) {
                    item.proportion_case_total_val = Number(item.proportion_case_total_val.replace('%', ''));
                  }

                  if (item.percent_c_case_count) {
                    item.percent_c_case_count = Number(item.percent_c_case_count.replace('%', ''));
                  }
                  if (item.percent_g_count) {
                    item.percent_g_count = Number(item.percent_g_count.replace('%', ''));
                  }
                  if (item.percent_case_total_val) {
                    item.percent_case_total_val = Number(item.percent_case_total_val.replace('%', ''));
                  }
                });
              }
              this.orginalData.content = this.$u.deepClone(res.data);
              this.endDate = cte;
            } else {
              this.$u.toast(res.msg);
            }
          })
          .catch((e) => {
            this.$modal.hideLoading();
            console.log(e);
            this.$u.toast('查询失败');
          });
      } else {
        this.hasTotal = false;
        const brandParams = {
          page: 1,
          limit: 20,
          paras: {
            comparedShow: '1',
            orgUuid: param.orgUuid,
            caseDateBegin: cts,
            caseDateEnd: cte,
            propType: this.fromEnum[this.from].propType,
          },
        };
        let currentTab = this.fromEnum[this.from].propType; // 01真烟  02假烟 03走私烟
        reportService
          .caseStatisticsListsNew(brandParams)
          .then((res) => {
            this.$modal.hideLoading();
            if (res.success) {
              let result = res.data;
              let totalCount = 0;
              result.forEach((element) => {
              element.percent_totalQty = element.percent_totalQty || '';
              element.percent_truthQty = element.percent_truthQty || '';
              element.percent_fakeQty = element.percent_fakeQty || '';
              element.percent_smuggleQty = element.percent_smuggleQty || '';
                element.percent_totalQty = element.percent_totalQty.replace('%', '');
                element.percent_truthQty = element.percent_truthQty.replace('%', '');
                element.percent_fakeQty = element.percent_fakeQty.replace('%', '');
                element.percent_smuggleQty = element.percent_smuggleQty.replace('%', '');
                if (currentTab == '01') {
                  element.totalQty = element.truthQty;
                  element.percent_totalQty = element.percent_truthQty;
                } else if (currentTab == '02') {
                  element.totalQty = element.fakeQty;
                  element.percent_totalQty = element.percent_fakeQty;
                } else if (currentTab == '03') {
                  element.totalQty = element.smuggleQty;
                  element.percent_totalQty = element.percent_smuggleQty;
                }
                totalCount += Number(element.totalQty);
              });
              // 计算占比 cig_case_qty_zb
              result.forEach((element) => {
                if (Number(element.totalQty) == 0) {
                  element.cig_case_qty_zb = 0;
                } else {
                  element.cig_case_qty_zb = ((Number(element.totalQty) / totalCount) * 100).toFixed(2);
                }
              });
              this.orginalData.content = this.$u.deepClone(result);
              console.log(this.$u.deepClone(result), this.orginalData.content, 'this.$u.deepClone(result)');
              this.endDate = cte;
            } else {
              this.$u.toast(res.msg);
            }
          })
          .catch((e) => {
            this.$modal.hideLoading();
            console.log(e);
            this.$u.toast('查询失败');
          });
      }
    },
    tabChange (e) {
      console.log('e====' + e);
      this.tabCurrent = e;
      this.keyCode = this.tabCurrent == 0 ? 'org_uuid' : '';
      this.orginalData.header = this.tabList[this.tabCurrent].header;
      this.orginalData.content = [];
      this.loadData();
    },
    dbClick (obj) {
      if (this.tabCurrent != 0) return;
      if (this.orgParam.orgRank > 1) return;
      // if(this.user.orgLevel == 3) return;
      this.orgParam.parentOrgUuid = this.orgParam.orgUuid;
      this.orgParam.parentOrgName = this.orgParam.orgName;
      this.orgParam.orgUuid = obj.org_uuid;
      this.orgParam.orgName = obj.org_name;
      this.orgParam.orgLevel = obj.org_level;
      this.orgParam.orgRank++;
      this.itemKeyUuid = '';
      this.itemKeyName = '';
      this.hasTotal = false;
      this.loadData();
    },
    clickItem (itm, key) {
      if (this.tabCurrent != 0) return;
      this.itemKeyUuid = itm.org_uuid;
      this.orgParam.orgLevel = itm.org_level;
      this.itemKeyName = itm.orgShortName;
    },
    refreshTb () {
      // 刷新操作，刷新暂不重置筛选条件
      this.orgParam.parentOrgUuid = '';
      this.orgParam.parentOrgName = '';
      this.itemKeyUuid = '';
      // this.endDate = moment().subtract(1, 'days').format("YYYY-MM-DD");
      // this.curTimeStart = moment().startOf('year').format('YYYY-MM-DD');
      // this.curTimeEnd = moment().subtract(1, 'days').format("YYYY-MM-DD");this.user.user.org.orgUuid
      this.orgParam.orgUuid = this.user.user.org.orgUuid; // 默认都用省的code
      this.orgParam.orgLevel = '01'; // "0" + this.user.orgLevel;
      this.orgParam.orgName = this.orgParam.areaName;
      this.orgParam.orgRank = 1;
      this.hasTotal = true;
      this.loadData();
    },
    timeChoice (f) {
      this.showTimeFlag = f;
      this.showTime = true;
    },
    timeChange (e) {
      const yesterday = moment().subtract(1, 'days').format('X');
      const choseTime = e.timestamp;
      if (Number(choseTime) > Number(yesterday)) {
        this.$u.toast('所选日期不能大于昨日');
        return false;
      }
      if (this.showSearch) {
        if (this.showTimeFlag == 0) {
          this.$refs.lscRef.timeOverStart = e.year + '-' + e.month + '-' + e.day;
        } else {
          this.$refs.lscRef.timeOverEnd = e.year + '-' + e.month + '-' + e.day;
        }
      }
    },
    searchTap (e) {
      if (e.isReset) {
        this.refreshTb();
      } else {
        this.showSearch = false;
        this.curTimeStart = e.data.timeOverStart;
        this.curTimeEnd = e.data.timeOverEnd;
        this.loadData();
      }
    },
    fabtrigger (act) {
      if (act.index === 0) {
        this.refreshTb();
      } else if (act.index === 1) {
        this.showSearch = true;
      }
    },
  },
};
</script>
<style scoped lang="scss">
.page {
  padding: 0;
}

.nav-right-icon {
  margin-right: 30rpx;
  font-size: 0.8rem;
  color: #fff;
}

.regie {
  height: 88rpx;
  padding: 0 $cm-content-paddng-row;
  font-size: 28rpx;
  display: inline-flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
}

.regie_txt_normal {
  font-weight: 400;
  color: #989ea1;
}

.regie_txt {
  font-weight: 600;
  color: #0070d2;
}

.regie_txt_divider {
  font-size: 12rpx;
  margin-left: 12rpx;
  margin-right: 12rpx;
}
</style>
